#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#define TEMP_BUFFER_SIZE 1024

void sendProtocol(int sock, char *protocol) {
	debug(protocol);
	if (send(sock, protocol, strlen(protocol), 0) != strlen(protocol)) {
		perror("send failed");
		exit(1);
	}
}

void recvProtocol(int sock, char *recvBuffer, int bufferSize) {
	int recvLen;
	if ((recvLen = recv(sock, recvBuffer, bufferSize-1, 0)) <= 0) {
		perror("recv failed");
		exit(1);
	}

	recvBuffer[recvLen] = '\0';
}



unsigned int downloadFile(int sock, char *filePath, unsigned int fileSize, int hashFlag) {
	char readBuffer[TEMP_BUFFER_SIZE];
	unsigned int readBytes, totalBytes, numHash;
	
	int fd = open(filePath, O_WRONLY | O_CREAT, 0664);
	
	totalBytes = numHash = 0;
	while (totalBytes < fileSize) {
		//if ((readBytes = read(sock, readBuffer, TEMP_BUFFER_SIZE)) <= 0) {
		if ((readBytes = readline(sock, readBuffer, TEMP_BUFFER_SIZE)) <= 0) {
					close(fd);
			return totalBytes;
		}
		writen(fd, readBuffer, readBytes);
		totalBytes += readBytes;
		
		if (hashFlag) {
			if ((totalBytes/TEMP_BUFFER_SIZE) > numHash) {
				numHash++;
				printf("#");
			}
		}
	}
	close(fd);
	printf("\n");
	
	return totalBytes;
}

unsigned int uploadFile(int sock, char *filePath, int hashFlag) {
	char readBuffer[TEMP_BUFFER_SIZE];
	unsigned int readBytes, totalBytes, numHash;
	
	int fd = open(filePath, O_RDONLY);
	
	if(fd <0){
		fprintf(stderr, "local: file not exist %s", filePath);
		return 0;
	}
	totalBytes = numHash = 0;
	//while ((readBytes = read(fd, readBuffer, TEMP_BUFFER_SIZE)) > 0) {
	while ((readBytes = readline(fd, readBuffer, TEMP_BUFFER_SIZE)) > 0) {
			writen(sock, readBuffer, readBytes);
		totalBytes += readBytes;
		
		if (hashFlag) {
			if ((totalBytes/TEMP_BUFFER_SIZE) > numHash) {
				numHash++;
				printf("#");
			}
		}
	}
	close(fd);
	printf("\n");
	
	return totalBytes;
}
